
-- Copyright (C) 2012 wgm.china@gmail.com
--init_config.lua is not OK
local cjson = require "cjson"
local config_table = ngx.shared.gcs_config   --声明ngx.shared.gcs_config
local ipshine_table = ngx.shared.gcs_ipshine   --声明ngx.shared.gcs_ipshine

-------------------

local cjson = require "cjson"
local mysql = require "resty.mysql"
local server_ip = ngx.var.arg_server or "192.168.2.133" 
local server_port = ngx.var.arg_port or "3306"
local server_user = ngx.var.arg_user or "root"
local server_passwd = ngx.var.arg_passwd or "gcstorage"
local server_db = ngx.var.arg_db or "JG"

local web_info_number = ngx.var.arg_storage_number or "s1"

--公共函数
string.split = function(s, p)

  local rt= {}
  string.gsub(s, '[^'..p..']+', function(w) table.insert(rt,w) end )
  return rt
end

function mysql_query(sql)
  local db = mysql:new()
  db:set_timeout(10000) -- 10 sec
  local result
  local ok, err, errno, sqlstate = db:connect({
    host = server_ip,
    port = server_port,
    database = server_db,
    user = server_user,
    password = server_passwd,
    max_packet_size=104857600})

  if not ok then
    --ngx.say("failed to connect mysql server: " , err , ": " , errno, " " , sqlstate)
    ngx.say("mysql_query connect error:"..err)
    return nil,"mysql_query connect error:"..err
  end

  local res, err, errno, sqlstate = db:query(sql)
  local ok, err1 = db:set_keepalive(0, 10)
  if not ok then
    ngx.say("mysql_query close connect error:"..err)
  end

  --close db
  if res then
    return res
  else
    return false,err
  end
end

--
----1.加载gcs_config到nginx.shared.gcs_config

local res,err = mysql_query("select C_KEY as GCS_KEY,C_VALUE as GCS_VALUE,C_TYPE as GCS_TYPE from gcs_config  where C_TYPE ='p'")
if not res then
  ngx.say(err)
  return
end
for i,v in pairs(res) do
  if type(v) == "table" then
    config_table:set(v.GCS_TYPE .. "_" .. v.GCS_KEY,v.GCS_VALUE)
  end
end
----1.加载vss_config完成


----2.加载gcs_ipshine到nginx.shared.gcs_ipshine


local res,err = mysql_query("select C_KEY,C_CDSL,C_KKMC,C_XSFX,C_SBBH,C_LKBH,C_ZPZS,sbxs,lx from base_sbxx where C_STATUS = 'using' ")
if not res then
  ngx.say(err)
  return
end
local n = 0
for i,v in pairs(res) do
  if type(v) == "table" then
  --[[
key  kkbh_ip
key  xsfx_ip
key  sbbh_ip
key  kkmc_ip
key  cdsl_ip
  --]]
    n = n+1
    ipshine_table:set("lkbh_"..v.C_KEY,v.C_LKBH)
    ipshine_table:set("xsfx_"..v.C_KEY,v.C_XSFX)
    ipshine_table:set("sbbh_"..v.C_KEY,v.C_SBBH)
    ipshine_table:set("kkmc_"..v.C_KEY,v.C_KKMC)
    ipshine_table:set("cdsl_"..v.C_KEY,v.C_CDSL)
    ipshine_table:set("zpzs_"..v.C_KEY,v.C_ZPZS)
    ipshine_table:set("xs_"..v.C_KEY,v.sbxs)
    ipshine_table:set("lx_"..v.C_KEY,v.lx)
  end
end



config_table:set("init_config",os.date("%Y-%m-%d %H:%M:%S",ngx.now()))
ngx.say("init_config:",os.date("%Y-%m-%d %H:%M:%S",ngx.now()))

ngx.say("n is "..n)
